/**
 * 
 */
package com.googlecode.pcapj;

import java.io.IOException;
import java.util.Iterator;

import org.bridj.Pointer;

import com.googlecode.pcapj.bridj.Wpcap;
import com.googlecode.pcapj.bridj.pcap_if;

/**
 * 
 */
class InterfacesImpl implements Interfaces{
	private CapturedFactory capturedFactory;
	private Pointer<pcap_if> current;
	private Pointer<Pointer<pcap_if>> alldevs;
	
	private Iterator<Interface> iterator = new Iterator<Interface>() {
		public void remove() {
			throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".remove()");
		}
		public Interface next() {
			Interface inter = null;
			if(current != Pointer.NULL){
				pcap_if pcap_if = current.get();
				inter = new InterfaceImpl(pcap_if, capturedFactory);
				current = pcap_if.next();
			}
			return inter;
		}
		
		public boolean hasNext() {
			return current != Pointer.NULL;
		}
	};
	/**
	 * @param alldevs 
	 */
	InterfacesImpl(
			Pointer<Pointer<pcap_if>> alldevs,
			CapturedFactory capturedFactory) {
		super();
		this.capturedFactory = capturedFactory;
		this.alldevs = alldevs;
		this.current = alldevs.get();
	}
	/* (non-Javadoc)
	 * @see java.lang.Iterable#iterator()
	 */
	public Iterator<Interface> iterator() {
		return iterator;
	}

	/* (non-Javadoc)
	 * @see java.io.Closeable#close()
	 */
	public void close() throws IOException {
		Pointer<Pointer<pcap_if>> alldevs = this.alldevs;
		if(alldevs != null){
			Wpcap.pcap_freealldevs(alldevs.get());
			alldevs.release();
		}
		this.alldevs = null;
	}
}
